/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.cqq.document;

import com.yunhoo.cqq.impl.IbatisDocument;
import com.yunhoo.cqq.model.CodeBase;
import com.yunhoo.cqq.model.Document;
import com.yunhoo.cqq.model.DocumentType;
import com.yunhoo.cqq.util.FileUploadDownloadToolKit;
import com.yunhoo.cqq.util.SysCode;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.util.tree.MyTreeNodeImpl;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import org.richfaces.component.UIDataTable;
import org.richfaces.event.TreeSelectionChangeEvent;
import org.richfaces.model.TreeNode;
import org.richfaces.model.TreeNodeImpl;

@ManagedBean(name = "documentUpdateBean")
@SessionScoped
public class DocumentUpdateBean {

    private HtmlInputText documentTypeCode = new HtmlInputText();
    private TreeNode rootNode = null;
    private DocumentType documentType;
    private UIDataTable data = null;
    private int counter = 1;
    private boolean showAble = true;
    private boolean editAble = false;
    private boolean addOrUpdate = true;
    private String rulecode = "0001";
    private List documentlist;
    private List<DocumentType> typelist;
    private List<DocumentType> typesublist;
    private List<Document> doclist = new ArrayList<Document>();

    public DocumentUpdateBean() {
        documentType = new DocumentType();
        documentlist = new ArrayList();

        typelist = new ArrayList<DocumentType>();
        typesublist = new ArrayList<DocumentType>();
    }

    public void add() {
        documentTypeCode.setReadonly(false);
        showAble = false;
        editAble = true;
        addOrUpdate = true;
        documentType = new DocumentType();
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void update() {
        documentTypeCode.setReadonly(true);
        showAble = false;
        editAble = true;
        addOrUpdate = false;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void save() {
        //判断部门代码属于第几级
        CodeBase base = SysCode.getGrade(documentType.getId(), rulecode);
        //检查代码是否重复、检查名称是否重复
        if (base.getGrade() != 0) {
            documentType.setGradeLevel(base.getGrade());
            documentType.setDescription(documentType.getName());
            List<DocumentType> temp = new ArrayList<DocumentType>();
            List<DocumentType> list = new ArrayList<DocumentType>();
            temp = IbatisDocument.checkDocRepeat(documentType);
            list = IbatisDocument.checkDoctypeParent(documentType);
            System.out.println("重复:" + temp.size() + "| 父节点:" + list.size());
            //修改父级代码
            if (addOrUpdate) {//插入
                if (list != null && list.size() == 0 && documentType.getGradeLevel() != 1) {
                    
                    ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "上级不存在");
                }
                if (temp != null && temp.size() > 0) {
                    
                    ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "代码或名称已存在");
                } else {
                    if (base.getGrade() > 1) {
                        base.setIsEnd(false);
                        IbatisDocument.updateDoctypeIsEnd(base);
                        System.out.println(base.getParentcode() + "++++");
                    }
                    documentType.setIsEnd("1");
                    IbatisDocument.insertDoctype(documentType);
                }
            }
            if (!addOrUpdate) {//修改
                if (list != null && list.size() == 0 && documentType.getGradeLevel() != 1) {
                    
                    ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "上级不存在");
                }
                if (temp != null && temp.size() > 0  && (!((DocumentType) temp.get(0)).getId().equals(documentType.getId())) || temp.size() > 1) {
                    
                    ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "代码或名称已存在");
                } else {
                    IbatisDocument.updateDoctype(documentType);
                }
            }
        } else {
            
            ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "该代码不符合编码规则");
        }
        loadTree();
        initStatus();
    }

    public void del() {
        //如果是末级部门，则删除
        if (!(documentType.getIsEnd().trim().equalsIgnoreCase("0"))) {
            //判断是否还有文档在引用该名称
            String id = documentType.getId();
            CodeBase base = SysCode.getGrade(id, rulecode);
            base.setGradeLevel(base.getGrade());
            //是否还有其他子集
            List principallist = IbatisDocument.getDoctypeSameLevel(base);
            if (principallist != null && principallist.size() == 0) {
                base.setIsEnd(true);
                IbatisDocument.updateDoctypeIsEnd(base);
            }
            IbatisDocument.deleteDoctype(documentType);
            loadTree();
            initStatus();
            FacesContext.getCurrentInstance().renderResponse();
        } else {
            
            ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "非末级部门，不可删除");
        }
    }

    public void initStatus() {
        showAble = true;
        editAble = false;
        addOrUpdate = true;
    }

    private void loadTree() {
        rootNode = new TreeNodeImpl();
        typelist = IbatisDocument.getRootDocType();
        addNodes(typelist, rootNode);
    }

    private void addNodes(List typelist, TreeNode node) {
        for (int i = 0; i < typelist.size(); i++) {
            
            DocumentType type = (DocumentType) typelist.get(i);
            
            Boolean isleaf = "1".equals(type.getIsEnd().trim()); //true : 是叶子节点
            
            TreeNodeImpl nodeImpl = new MyTreeNodeImpl(isleaf,type);
            
            node.addChild(type.getId(), nodeImpl);
            
            type.setGradeLevel(type.getGradeLevel() + 1);
            if (!isleaf) {
                typesublist = IbatisDocument.getSubDocType(type);
                addNodes(typesublist, nodeImpl);
            }
        }
    }

    public void selectedDocumentType2(TreeSelectionChangeEvent event) {//文档下载侦听
        documentType = (DocumentType) TreeUtil.listener(event);
        if (documentType != null) {
            String typeid = documentType.getId();
            String name = documentType.getName();
            doclist = new ArrayList<Document>();
            doclist = IbatisDocument.getSelectDocType(typeid);
            for (Document d : doclist) {
                try {
                    String str = new String(d.getUrl().getBytes("utf-8"), "iso-8859-1");
                    d.setUrl(str);
                } catch (UnsupportedEncodingException ex) {
                    Logger.getLogger(DocumentUpdateBean.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void selected2(TreeSelectionChangeEvent event) {//文档类型管理侦听
        documentType = (DocumentType) TreeUtil.listener(event);
        if (documentType != null) {
            String typeid = documentType.getId();
            String name = documentType.getName();
            doclist = new ArrayList<Document>();
            doclist = IbatisDocument.getSelectDocType(typeid);
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void selectedDocumentType(TreeSelectionChangeEvent event) {//文档上传侦听
        documentType = (DocumentType) TreeUtil.listener(event);
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void download(Document row) {
        Document  doc = row;
        String fileName = doc.getUrl();     
        int dirLen = doc.getUrl().lastIndexOf("\\");    
        fileName = fileName.substring(0,dirLen) + "\\" +  doc.getDescription();
        FileUploadDownloadToolKit.download(fileName);
    }
    
    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }

    public DocumentType getDocumentType() {
        return documentType;
    }

    public void setDocumentType(DocumentType documentType) {
        this.documentType = documentType;
    }

    public HtmlInputText getDocumentTypeCode() {
        return documentTypeCode;
    }

    public void setDocumentTypeCode(HtmlInputText documentTypeCode) {
        this.documentTypeCode = documentTypeCode;
    }

    public List getDocumentlist() {
        return documentlist;
    }

    public void setDocumentlist(List documentlist) {
        this.documentlist = documentlist;
    }

    public boolean isEditAble() {
        return editAble;
    }

    public void setEditAble(boolean editAble) {
        this.editAble = editAble;
    }

    public TreeNode getTreeNode() {
        if (this.rootNode == null) {
            loadTree();
        }
        return rootNode;
    }

    public void setRootNode(TreeNode rootNode) {
        this.rootNode = rootNode;
    }

    public String getRulecode() {
        return rulecode;
    }

    public void setRulecode(String rulecode) {
        this.rulecode = rulecode;
    }

    public boolean isShowAble() {
        return showAble;
    }

    public void setShowAble(boolean showAble) {
        this.showAble = showAble;
    }

    public List<DocumentType> getTypelist() {
        return typelist;
    }

    public void setTypelist(List<DocumentType> typelist) {
        this.typelist = typelist;
    }

    public List<DocumentType> getTypesublist() {
        return typesublist;
    }

    public void setTypesublist(List<DocumentType> typesublist) {
        this.typesublist = typesublist;
    }

    public List<Document> getDoclist() {
        return doclist;
    }

    public void setDoclist(List<Document> doclist) {
        this.doclist = doclist;
    }

    public UIDataTable getData() {
        return data;
    }

    public void setData(UIDataTable data) {
        this.data = data;
    }
    public static void main(String[] args) {
        System.out.println(new Date());
    }
}
